import { location } from "./getLocation";
import { pet } from "./pet";
import { getItemFromGui, getItemSBID, getItemUUID } from "./utils";

class petmanager {
    savedDate = {};
    currentProfile = "";

    /**
     * @type {pet[]}
     */
    pets = [];
    /**
     * @type {pet | null}
     */
    currentPet = null;

    constructor() {
        this.loadFromFile();
        this.load();
        this.init();
    }

    loadFromFile() {
        if(FileLib.exists("./config/ChatTriggers/modules/BabyzombieAddons/config/pets.json")) {
            try {
                let dataInFile = JSON.parse(FileLib.read("./config/ChatTriggers/modules/BabyzombieAddons/config/pets.json"));
                for (let profile in dataInFile) {
                    this.savedDate[profile] = { currentPet: null, pets: [] };
                    this.savedDate[profile].currentPet = dataInFile[profile].currentPet ?? null;
                    this.savedDate[profile].pets = dataInFile[profile].pets.map(petInfo => new pet(petInfo));
                }
            } catch (error) {}
        }
    }
    saveToFile() {
        FileLib.write("./config/ChatTriggers/modules/BabyzombieAddons/config/pets.json", JSON.stringify(this.savedDate,null,4), true);
    }

    load() {
        if(this.savedDate[location.SBProfile]) {
            this.pets = this.savedDate[location.SBProfile].pets;
            this.currentPet = this.savedDate[location.SBProfile].currentPet ?? null;
            this.currentProfile = location.SBProfile;
        }
    }
    save() {
        this.savedDate[location.SBProfile] = { pets: this.pets, currentPet: this.currentPet ?? null };
    }

    addPet(petInfo) { this.pets.push(new pet(petInfo)); this.save(); }
    removePet(uuid) { this.pets = this.pets.filter(pet => pet.uuid !== uuid); this.save(); }
    getPet() { return this.currentPet; }

    static getPetInfo(item) {
        return item?.getNBT()?.getCompoundTag("tag")?.getCompoundTag("ExtraAttributes")?.getString("petInfo");
    }

    init() {
        //加载 和 存档切换
        register("chat", (id,event) => {
            if(location.inSkyblock && this.currentProfile !== Player.getUUID() + '_' + id) {
                this.save(); this.load();
            }
        }).setCriteria("Profile ID: ${id}")

        //保存文件
        register("gameUnload", () => { this.save(); this.saveToFile(); })
        register("serverDisconnect", () => { this.save(); this.saveToFile(); })

        //自动宠物
        const autoPetRulelReg = /Autopet equipped your \[Lvl ([0-9]{1,3})\]( \[[0-9]{1,4}✦\])? ([a-zA-Z0-9_\- ✦]+)! VIEW RULE/;
        register("packetReceived", (packet,event) => {
            if(packet.func_179841_c() == 2) return;
            let message = new Message(packet.func_148915_c());
            if(!location.inSkyblock) return;
            let msgArg = autoPetRulelReg.exec(message.getUnformattedText().removeFormatting());
            if(!msgArg) return;
            let level = msgArg[1];
            let petname = msgArg[3];
            let text = message.getMessageParts().filter(e => e.getHoverValue() && e.getHoverValue().includes("Autopet Rule"))[0]?.getHoverValue().removeFormatting();
            let item = text.match(/Held Item: (.+)/i)[1];
            this.currentPet = this.pets.find(pet => pet.getName().replace(/_/g," ").toLowerCase() == petname.toLowerCase().replace(" ✦","") && pet.getLevel() == parseInt(level) && (item == null || pet.getHeldItem().removeFormatting() == item.removeFormatting()));
        }).setFilteredClass(net.minecraft.network.play.server.S02PacketChat)

        //使用宠物并添加到菜单
        register("playerInteract", (action,pos,event) => {
            if(!location.inSkyblock) return;
            let heldItem = Player.getHeldItem();
            if(heldItem && getItemSBID(heldItem) == "PET") this.addPet(petmanager.getPetInfo(heldItem));
        })

        //菜单内选择或取出
        register("guiMouseClick", (mx,my,button,gui,event) => {
            if(!location.inSkyblock) return;
            let item = getItemFromGui(gui);
            if(!item || getItemSBID(item) !== "PET") return;
            switch (button) {
                case 1:
                    this.removePet(getItemUUID(item));
                    break;
                case 0:
                    if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) break;
                default:
                    this.currentPet = this.pets.find(pet => pet.getUUID() == getItemUUID(item));
                    break;
            }
        })

        //获取菜单内的宠物
        let lastGuiOpenTime = 0;
        let lastGuiCloseTime = 0;
        register("guiOpened", (gui,event) => {
            if(!location.inSkyblock) return;
            lastGuiOpenTime = Date.now();
            lastGuiCloseTime = 0;
        })
        register("guiClosed", (event) => { lastGuiCloseTime = Date.now(); })
        register("step", () => { if(Date.now() - lastGuiCloseTime > 1000) {lastGuiOpenTime = 0; lastGuiCloseTime = 0;} }).setDelay(1)

        register("renderItemIntoGui", (item,x,y,event) => {
            try {
                if(!location.inSkyblock || lastGuiOpenTime == 0) return;
                let container = Player.getContainer();
                if(!container || !container.getName().removeFormatting().startsWith("Pets") || item.getName().removeFormatting() !== "Close") return;
                let pets = container.getItems().filter(item => item && getItemSBID(item) == "PET" && item.getLore().filter(lore => lore.removeFormatting() == "Right-click to convert to an item!").length > 0);
                pets.forEach(pet => {
                    try {
                        this.removePet(getItemUUID(pet));
                        this.addPet(petmanager.getPetInfo(pet));
                        if(pet.getLore().filter(lore => lore.removeFormatting() == "Click to despawn!").length > 0) this.currentPet = this.pets.find(petInPets => petInPets.getUUID() == getItemUUID(pet));
                    } catch (error) {}
                })
                lastGuiOpenTime = 0;
            } catch (error) {lastGuiOpenTime = 0;}
        })
    }
}

export default new petmanager();